package com.blog.controller;

import com.blog.entity.Blogger;
import com.blog.service.BloggerService;
import com.blog.util.CryptographyUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
  博主登陆相关
 */
@Controller
@RequestMapping("/blogger")
public class BloggerController {
    @Resource
    private BloggerService bloggerService;

    @RequestMapping("/login")
    public String login(Blogger blogger, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();//Subject
        //通过前台输入的用户名和经过加密的密码生成一个令牌
        UsernamePasswordToken token = new UsernamePasswordToken(blogger.getUserNumber(), CryptographyUtil.md5(blogger.getPassword(), "SunBingRui"));
        try {
            //传递token给shiro的realm
            subject.login(token);
            return "redirect:/admin/main.jsp";//登陆成功重定向到后台界面
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("blogger", blogger);
            request.setAttribute("errorInfo", "用户名或密码错误");
        }
        return "login";
    }

    //关于博主
    @RequestMapping("/aboutMe/{id}")
    public ModelAndView aboutMe(@PathVariable("id") Integer id, HttpServletRequest req, HttpServletResponse res) throws Exception {
        if(id==null){
            req.getRequestDispatcher("/500.jsp").forward(req,res);
        }
        ModelAndView mav = new ModelAndView();
        mav.addObject("blogger", bloggerService.getUserById(id));
        mav.addObject("mainPage", "foreground/blogger/info.jsp");
        mav.addObject("pageTitle", "高手简介");
        mav.setViewName("index");
        return mav;
    }
}
